package com.myblog.utils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

public class CaptchaUtils {

    //图片宽度
    private int width = 86;
    //图片高度
    private int height = 37;
    /**
     * 用于生成带四位数字验证码的图片
     */
    public void imageCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");

        OutputStream os = response.getOutputStream();
        //返回验证码和图片的map
        Map<String,Object> map = VerifyUtils.getImageCode(width,height,os);
        //设置验证码到session（转为小写）
        HttpSession session = request.getSession(true);
        session.setAttribute("_code", map.get("strEnsure").toString().toLowerCase());
        String code = (String) session.getAttribute("_code");
        System.out.println("存储验证码：" + code);
        request.getSession().setAttribute("codeTime",new Date().getTime());
        try{
            ImageIO.write((BufferedImage)map.get("image"),"jpg",os);
        } catch (IOException e){
            System.err.println(e.getMessage());
        } finally{
            if(os != null){
                os.flush();
                os.close();
            }
        }
    }
}
